package com.google.ant;

import org.apache.tools.ant.Task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class CodeFormatter extends Task {
  private String recursive;
  private ArrayList<Dir> dirs = new ArrayList<Dir>();
  
  public void setRecursive(String recursive) {
    this.recursive = recursive;
  }
  
  public Dir createDir() {
    Dir dir = new Dir();
    dirs.add(dir);
    return dir;
  }
  
  public class Dir {
    private String text;
    
    public void addText(String text) {
      this.text = text;
    }
    
    public String getText() {
      return this.text;
    }
  }
  
  @Override
  public void execute() {
    for (Dir dir : dirs) {
      log("Check dir " + dir.getText());
      formatDir(dir.getText());
    }
  }
  
  private void formatDir(String dir) {
    File d = new File(dir);
    if (!d.exists()) return;
    for (File f : d.listFiles()) {
      if (f.isDirectory()) {
        if ("1".equals(this.recursive)) formatDir(f.getPath());
      }
      else {
        formatFile(f.getPath());
      }
    }
  }
  
  private void formatFile(String path) {
    try {
      StringBuilder orig = new StringBuilder();
      StringBuilder sb = new StringBuilder();
      BufferedReader br = new BufferedReader(new FileReader(path));
      String line;
      while ((line = br.readLine()) != null) {
        orig.append(line + "\n");
        line = line.replaceAll("\\t", "  ");
        line = line.replaceAll("\\s*$", "");
        sb.append(line + "\n");
      }
      br.close();
      
      if (orig.toString().equals(sb.toString())) return;
      log("Format file " + path);
      
      FileOutputStream fos = new FileOutputStream(path); 
      fos.write(sb.toString().getBytes());
      fos.close();
    } catch (IOException e) {
      // don't process if error
    }
  }
}
